﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Power.Model;
using Power.BLL;
using JN.Utility;
using DevExpress.XtraTreeList.Nodes;

namespace Power.MeterInfo
{
    public partial class MeterInfo : DevExpress.XtraEditors.XtraForm
    {
        #region property
        private Meter_infoBLL meterBLL = new Meter_infoBLL();
        private bool isAdd;
        private string station_Id;
        #endregion
        public MeterInfo()
        {
            InitializeComponent();
        }

        private void MeterInfo_Load(object sender, EventArgs e)
        {
            using (new DevExpress.Utils.WaitDialogForm("正在加载数据...", "Please Wait..."))
            {
                station_Id = Manager.SystemStatus.Instance.Station_id;
                InitalizeUI();
                DisplayButton(false);
                EnanbleAllTextInput(false);                
                LoadChest("");
                LoadStation();
                LoadPort();
            } 
        }
        /// <summary>
        /// 初始化界面，加载treelist
        /// </summary>
        private void InitalizeUI()
        {
            try
            {
                TreeListNode node;
                treeList1.Nodes.Clear();
                node = treeList1.AppendNode(new object[] { "电表", "电表", null, null }, null);
                node.StateImageIndex = 1;
                //node2 = tlstHead.AppendNode(new object[] { "Step Name", "Step Name", null, null }, null);

                //get data from table   
                DataTable dtData;
                if (!string.IsNullOrEmpty(station_Id))
                {
                    dtData = meterBLL.GetList(" station_id ='" + station_Id + "' ").Tables[0];
                }
                else
                {
                    dtData = meterBLL.GetAllList().Tables[0];
                }
                
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    node = treeList1.AppendNode(new object[] { dtData.Rows[i]["meter_id"] + "_" + dtData.Rows[i]["meter_name"], dtData.Rows[i]["meter_id"], null, null }, 0);
                    node.StateImageIndex = 0;

                    //node2 = tlstHead.AppendNode(new object[] { dtStep.Tables[0].Rows[i]["step_name"], i, null, null }, 1);
                }
                //node.ExpandAll();
                treeList1.ExpandAll();
                this.treeList1.EndUnboundLoad();

                DisplayForm("");    //initalize list 

            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 按键显示
        /// </summary>
        /// <param name="isAdd"></param>
        private void DisplayButton(bool isAdd)
        {
            try
            {
                if (isAdd)
                {
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnQuery.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                    btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                }
                else
                {
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnQuery.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;

                    btnSave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnCancel.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                    txtId.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 输入状态
        /// </summary>
        /// <param name="isCanInput"></param>
        private void EnanbleAllTextInput(bool isCanInput)
        {
            try
            {
                txtId.Properties.ReadOnly = !isCanInput;
                txtName.Properties.ReadOnly = !isCanInput;
                txtChestId.Properties.ReadOnly = !isCanInput;
                txtEntyeryTime.Properties.ReadOnly = !isCanInput;
                txtInUse.Properties.ReadOnly = !isCanInput;                
                txtKind.Properties.ReadOnly = !isCanInput;
                txtLogo.Properties.ReadOnly = !isCanInput;
                txtOverTime.Properties.ReadOnly = !isCanInput;
                txtRateCurrent.Properties.ReadOnly = !isCanInput;
                txtRateCurrent6.Properties.ReadOnly = !isCanInput;
                txtStationId.Properties.ReadOnly = !isCanInput;
                txtNode.Properties.ReadOnly = !isCanInput;

                txtKeyinTime.Properties.ReadOnly = true;
                txtKeyinUser.Properties.ReadOnly = true;
                cmbPort.Properties.ReadOnly = !isCanInput;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 显示界面信息
        /// </summary>
        /// <param name="eqGrpID"></param>
        private void DisplayForm(string meterId)
        {
            try
            {
                if (meterId != "")
                {
                    //get eq info                    
                    Meter_info  mMeter = meterBLL.GetModel(meterId);
                    if (mMeter == null) return;
                    txtId.Text = mMeter.meter_id;
                    txtName.Text = mMeter.meter_name;
                    txtChestId.EditValue = mMeter.chest_id;
                    txtEntyeryTime.Text = mMeter.entery_time.ToString();
                    txtInUse.SelectedIndex =(int)mMeter.is_use;
                    txtKeyinTime.Text = mMeter.keyin_time.ToString();
                    txtKeyinUser.Text = mMeter.keyin_user;
                    txtKind.Text = mMeter.kind;
                    txtLogo.Text = mMeter.logo;
                    txtOverTime.Text = mMeter.overdue_date.ToString();
                    txtRateCurrent.Value =(decimal)mMeter.rated_current;
                    txtRateCurrent6.Value = (decimal)mMeter.rated_current_60;
                    txtStationId.EditValue = mMeter.station_id;
                    txtNode.Value = (decimal)mMeter.node;
                    cmbPort.Text = mMeter.com_port;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 加载站点
        /// </summary>
        private void LoadStation()
        {
            try
            {
                Station_infoBLL stationBLL = new Station_infoBLL();
                DataTable dtData = stationBLL.GetAllList().Tables[0];
                txtStationId.Properties.ValueMember = "station_id";
                txtStationId.Properties.DisplayMember = "station_name";
                txtStationId.Properties.DataSource = dtData;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 加载Port
        /// </summary>
        private void LoadPort()
        {
            try
            {
                Com_infoBLL comBLL = new Com_infoBLL();
                string sql = " station_id='"+ Manager.SystemStatus.Instance.Station_id +"' ";
                DataTable dtData = comBLL.GetList(sql).Tables[0];

                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    cmbPort.Properties.Items.Add(dtData.Rows[i]["com_port"].ToString());
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        /// <summary>
        /// 加载电表柜子
        /// </summary>
        /// <param name="chest_id"></param>
        private void LoadChest(string station_id)
        {
            try
            {
                Chest_infoBLL chestBLL = new Chest_infoBLL();

                DataTable dtData;
                if (station_id != "")
                {
                    //show 
                    dtData = chestBLL.GetList(" station_id ='" + station_id + "' ").Tables[0];
                }
                else
                {
                    //show all
                    dtData = chestBLL.GetAllList().Tables[0];
                }
                txtChestId.Properties.ValueMember = "chest_id";
                txtChestId.Properties.DisplayMember = "chest_desc";
                txtChestId.Properties.DataSource = dtData;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }
        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                isAdd = true;                
                txtId.Text = "";
                txtName.Text = "";
                txtChestId.EditValue = "";
                txtEntyeryTime.Text = "";
                txtInUse.SelectedIndex = 0;
                txtKeyinTime.Text = "";
                txtKeyinUser.Text = "";
                txtKind.Text = "";
                txtLogo.Text = "";
                txtOverTime.Text = "";
                txtRateCurrent.Value = 0;
                txtRateCurrent6.Value = 0;
                txtStationId.EditValue = "";
                txtNode.Value = 0;
                cmbPort.Text = "";
                //init param

                DisplayButton(true);
                EnanbleAllTextInput(true);
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (txtId.Text.Trim() == "")
                {
                    XtraMessageBox.Show("请选择修改电表!!");
                    return;
                }
                isAdd = false;
                EnanbleAllTextInput(true);
                txtId.Enabled = false;
                txtStationId.Properties.ReadOnly = true;
                txtChestId.Properties.ReadOnly = true;
                DisplayButton(true);
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (txtId.Text == "")
            {
                XtraMessageBox.Show("请选择需要删除的电表");
                return;
            }
            DialogResult result = XtraMessageBox.Show("确认删除此电表信息??", "警告", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                if (meterBLL.Delete(txtId.Text.Trim()))
                {
                    XtraMessageBox.Show("删除成功!!");
                }
                else
                {
                    XtraMessageBox.Show("删除失败!!");
                }
            }
            InitalizeUI();
        }

        private void btnQuery_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (new DevExpress.Utils.WaitDialogForm("正在加载数据...", "Please Wait..."))
            {
                InitalizeUI();
            } 
        }

        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            if (SaveData())
            {
                //refresh data
                XtraMessageBox.Show("保存成功!!");
                InitalizeUI();
                EnanbleAllTextInput(false);
                DisplayButton(false);
            }
            else
            {
                XtraMessageBox.Show("保存失败!!");
            } 
        }

        private void btnCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DisplayButton(false);
            EnanbleAllTextInput(false);
        }
        private bool SaveData()
        {
            bool ret = false;
            try
            {
                if (txtId.Text == "")
                {
                    XtraMessageBox.Show("请输入电表编码!!");
                    return ret;
                }
                if (txtName.Text == "")
                {
                    XtraMessageBox.Show("请输入电表名称!!");
                    return ret;
                }
                if (isAdd)
                {
                    if (meterBLL.Exists(txtId.Text))
                    {
                        XtraMessageBox.Show("电表编码已经存在，请重新输入!!");
                        txtId.Focus();
                        return ret;
                    }

                    //save param
                    Meter_info mMeter = new Meter_info();

                    mMeter.chest_id = txtChestId.EditValue.ToString() ;
                    mMeter.entery_time = txtEntyeryTime.DateTime;
                    mMeter.is_use = txtInUse.SelectedIndex;
                    mMeter.keyin_time = DateTime.Now;
                    mMeter.keyin_user = Manager.SystemStatus.Instance.Login_user;
                    mMeter.kind = txtKind.Text;
                    mMeter.logo = txtLogo.Text;
                    mMeter.meter_id = txtId.Text;
                    mMeter.meter_name = txtName.Text;
                    mMeter.overdue_date = txtOverTime.DateTime;
                    mMeter.rated_current = txtRateCurrent.Value;
                    mMeter.rated_current_60 = txtRateCurrent6.Value;
                    mMeter.station_id = txtStationId.EditValue.ToString();
                    mMeter.node = (int)txtNode.Value;
                    mMeter.com_port = cmbPort.Text;

                    //add new step
                    ret = meterBLL.Add(mMeter);
                    return ret;
                }
                else
                {

                    Meter_info mMeter = meterBLL.GetModel(txtId.Text);

                    mMeter.chest_id = txtChestId.EditValue.ToString();
                    mMeter.entery_time = txtEntyeryTime.DateTime;
                    mMeter.is_use = txtInUse.SelectedIndex;
                    mMeter.keyin_time = DateTime.Now;
                    mMeter.keyin_user = Manager.SystemStatus.Instance.Login_user;
                    mMeter.kind = txtKind.Text;
                    mMeter.logo = txtLogo.Text;
                    mMeter.meter_id = txtId.Text;
                    mMeter.meter_name = txtName.Text;
                    mMeter.overdue_date = txtOverTime.DateTime;
                    mMeter.rated_current = txtRateCurrent.Value;
                    mMeter.rated_current_60 = txtRateCurrent6.Value;
                    mMeter.station_id = txtStationId.EditValue.ToString();
                    mMeter.node = (int)txtNode.Value;
                    mMeter.com_port = cmbPort.Text;

                    //add new step
                    ret = meterBLL.Update(mMeter);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                return false;
            }
        }
        private bool IsValid()
        {
            bool ret = false;
            try
            {
                if (string.IsNullOrEmpty(txtId.Text))
                {
                    XtraMessageBox.Show("请输入编码!!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtName.Text))
                {
                    XtraMessageBox.Show("请输入名称!!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtStationId.Text))
                {
                    XtraMessageBox.Show("请选择站点!!");
                    return ret;
                }
                if (string.IsNullOrEmpty(txtChestId.Text))
                {
                    XtraMessageBox.Show("请选择柜子号!!");
                    return ret;
                }
                if (txtEntyeryTime.Text == "")
                {
                    XtraMessageBox.Show("请选择投入使用时间!!");
                    return ret;
                }
                if (txtOverTime.Text == "")
                {
                    XtraMessageBox.Show("请选择过期时间!!");
                    return ret;
                }
                if ( DateTime.Compare(txtOverTime.DateTime,txtEntyeryTime.DateTime) <= 0)
                {
                    XtraMessageBox.Show("过期日期输入有误!!");
                    return ret;
                }
                if (txtRateCurrent.Value < 0)
                {
                    XtraMessageBox.Show("额定电流输入有误!!");
                    return ret;
                }
                if (txtRateCurrent6.Value < 0)
                {
                    XtraMessageBox.Show("额定电流60% 输入有误!!");
                    return ret;
                }
                //if (txtRateCurrent.Value <= txtRateCurrent6.Value)
                //{
                //    XtraMessageBox.Show("额定电流60% 输入有误!!");
                //    return ret;
                //}                

                ret = true;
                return ret;
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
                return false;
            }
        }
        private void treeList1_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnSave.Visibility == DevExpress.XtraBars.BarItemVisibility.Always)
                {
                    XtraMessageBox.Show("正在修改模式，不能切换!");
                    return;
                }
                TreeListNode clickedNode = this.treeList1.FocusedNode;
                string disPlayText = clickedNode.GetDisplayText(0);
                if (disPlayText.ToUpper() != "电表")
                {
                    DisplayForm(disPlayText.Substring(0, clickedNode.GetDisplayText(0).IndexOf("_")));
                }
            }
            catch (Exception ex)
            {
                SystemLogger.Write(ex);
            }
        }

        private void txtStationId_Click(object sender, EventArgs e)
        {
            LoadStation();
            txtStationId.ShowPopup();
        }

        private void txtChestId_Click(object sender, EventArgs e)
        {
            if (txtStationId.Text == "")
            {
                //show all
                LoadChest("");
            }
            else
            {
                //show list
                LoadChest(txtStationId.EditValue.ToString());
            }
            txtChestId.ShowPopup();
        }
    }
}